﻿using System;
using System.Collections.Generic;
using System.Text;
using SyncCommon;
using System.Text.RegularExpressions;
using System.IO;

namespace SyncWebSite
{
    /// <summary>
    /// 易居客
    /// </summary>
    public class SyncEJU : SyncHouseBase
    {
        private string cd;
        private string ptk;
        private string targetID = "";
        private string logintime = "1346058712095";
        private List<string> retImages = new List<string>();
        private Dictionary<string, string> loginCookies = new Dictionary<string, string>();
        private string CityID = "2";
        private string CityShort = "sh";

        private string AgentID = "";
        private string CUID = "";
        private string HouseID = "";
        private string TargetBySearch = "";
        private string TargetUrl = "";
        private Encoding retEncoding = Encoding.GetEncoding("GB2312");
        private Encoding inputEncoding = Encoding.GetEncoding(936);
        public SyncEJU(string user, string password)
            : base(user, password)
        {

        }

        #region SyncHouseBase

        public override bool CheckLogin()
        {
            WebRequest request = new WebRequest("http://agent.eju.com/login?ver=3.0", FormType.FormUrlEncode, Encoding.UTF8, retEncoding);
            request.Cookies = loginCookies;
            request.AllowRedirect = false;
            request.AddContent("username", UserName);
            request.AddContent("password", Password);
            string ret = request.SendWaitString();
            if (request.TransferLocation == "/index/center")
            {
                request = new WebRequest("http://agent.eju.com/index/center");
                request.Cookies = loginCookies;
                request.AllowRedirect = true;
                request.ReturnEncoding = retEncoding;

                ret = request.GetResouceStr();
                if ((!string.IsNullOrEmpty(ret) && ret.Contains("修改个人信息")) && ret.Contains("退出"))
                {
                    return true;
                }
                return false;
            }
            else
            {
                return false;
            }

        }


        public override bool AddSaleHouse(HouseInfo info, ref string targetID)
        {
            UpdateCurrentStatus(StandardProgress.InitalData);
            //GetCityShort(info.City);
            string error = "";
            try
            {
                if (!CheckLogin())
                {
                    UpdateCurrentStatus(StandardProgress.Failed, "登录失败");
                    return false;
                }
                else
                {
                    string errorInfor = "";
                    if (!CommonCheck(info, true, ref errorInfor))
                    {
                        UpdateCurrentStatus(StandardProgress.Failed, errorInfor);
                        return false;
                    }
                    GetAgentID();
                    WebRequest request = new WebRequest("http://agent.eju.com/housereal/uploadpic?ver=3.0", FormType.FormUrlEncode, retEncoding, retEncoding);
                    //WebRequest request = new WebRequest("http://agent.eju.com/housereal/addhouse", FormType.FormUrlEncode, retEncoding, retEncoding);
                    request.Cookies = loginCookies;
                    FillPostData(info, request);
                    request.AddContent("saleprice", info.Price);
                    UpdateCurrentStatus(StandardProgress.PosData);

                    string ret = request.SendWaitString();


                    targetID = HtmlHelper.GetTextOrHiddenValueByName(ret, "houseid");
                    if ((ret.Contains("房屋基本信息") && ret.Contains("房屋图片信息")) && !string.IsNullOrEmpty(targetID))
                    {
                        WebRequest stepRequest = new WebRequest("http://agent.eju.com/housereal/save?ver=3.0&step=2", FormType.FormUrlEncode, inputEncoding, retEncoding);
                        stepRequest.Cookies = loginCookies;

                        SyncImage(info, stepRequest, targetID);

                        ret = stepRequest.SendWaitString();
                        if (!string.IsNullOrEmpty(ret) && ret.Contains("房源发布成功"))
                        {
                            TargetUrl = string.Format("http://sh.esf.sina.com.cn/detail/{0}", targetID);
                            UpdateCurrentStatus(StandardProgress.Sucess, GetImageError(info), targetID, TargetUrl);
                            return true;
                        }
                        error = GetError(ret);
                        goto erroHanlder;
                        //GetError
                    }
                    if (!string.IsNullOrEmpty(ret))
                    {
                        if (ret.Contains("canAdmin"))
                        {
                            error = "您没有发布二手房的权限";
                           
                        }
                        if (ret.Contains("您已发布过类似信息"))
                        {
                            error = "您已发布过类似信息,请修改房源信息后重新发布";
                        }
                        if (ret.Contains("需要您的进一步确认"))
                        {
                            error = "已有相似房源添加";
                        }
                        if (ret.Contains("立即发布"))
                        {
                            error = "网站上是否可以成功发布此小区信息或者表单信息不正确";
                        }
                    }
                    if (string.IsNullOrEmpty(error))
                    {
                        error = "发布失败。发布消息格式不正确";
                    }
                }
            }
            catch (System.Net.WebException exp)
            {
                error = WebError;
            }
            catch (Exception exp)
            {
                LogCenter.Log("易居客信息提交", exp);
                error = exp.Message;
            }
        erroHanlder:
            UpdateCurrentStatus(StandardProgress.Failed, error);
            return false;
        }

        private void FillPostData(HouseInfo info, WebRequest request)
        {
            request.AddContent("tradetype", GetTradeType(info));
            //小区信息获取
            GetEsateInformation(request, info);
            
            request.AddContent("propertype", GetHouseType(info));
            request.AddContent("complete", GetAge(info.Age));
            request.AddContent("model_room", info.Room);
            request.AddContent("model_hall", info.Hall);
            request.AddContent("model_toilet", info.WashRoom);
            request.AddContent("model_balcony", "0");
            request.AddContent("buildingarea", info.Area);
            request.AddContent("floor", info.CurrentFloor);
            request.AddContent("total_floor", info.Floors);
            request.AddContent("direction", GetToward(info.Toward));
            request.AddContent("fitment", GetDecoration(info.Decoration));
    

            request.AddContent("housecode", "");
            request.AddContent("save_action", "insert");
            request.AddContent("change", "");
            request.AddContent("sourcetype", "1");
            request.AddContent("cuid", AgentID);
            request.AddContent("status", "0");
            request.AddContent("tab", "1");
            request.AddContent("house_pro", "1");
            request.AddContent("next_pro", "2");

            request.AddContent("companyid", "0");
            request.AddContent("saletype", "4");

            request.AddContent("agentid", AgentID);//代理ID

            request.AddContent("shopid", "0");
            request.AddContent("child_companyid", "0");



            request.AddContent("housetitle", info.Title);
            request.AddContent("house_desc", info.Description);
            request.AddContent("save_action", "insert");
            request.AddContent("change", "");
            request.AddContent("id", "");

            request.AddContent("__hash__", "");
            request.AddContent("houseid", HouseID);
            request.AddContent("tab", "1");
        }

        public override bool AddRentHouse(HouseInfo info, ref string targetID)
        {
            UpdateCurrentStatus(StandardProgress.InitalData);
            //GetCityShort(info.City);
            string error = "";
            try
            {
                if (!CheckLogin())
                {
                    UpdateCurrentStatus(StandardProgress.Failed, "登录失败");
                    return false;
                }
                else
                {
                    string errorInfor = "";
                    if (!CommonCheck(info, false, ref errorInfor))
                    {
                        UpdateCurrentStatus(StandardProgress.Failed, errorInfor);
                        return false;
                    }
                    GetAgentID();
                    WebRequest request = new WebRequest("http://agent.eju.com/housereal/uploadpic?ver=3.0", FormType.FormUrlEncode, retEncoding, retEncoding);
                    request.Cookies = loginCookies;
                    FillPostData(info, request);

                    #region Rent related information
                    request.AddContent("rentprice", info.MonthPrice);
                    request.AddContent("rentergender", "");
                    request.AddContent("renttype",GetRentType( info));
                    request.AddContent("saleprice", info.MonthPrice);
                    GetPayment(request, info);
                    #endregion

                    UpdateCurrentStatus(StandardProgress.PosData);
                    //SyncImage(info, request,HouseID);
                    string ret = request.SendWaitString();

                    targetID = HtmlHelper.GetTextOrHiddenValueByName(ret, "houseid");
                    if ((ret.Contains("房屋基本信息") && ret.Contains("房屋图片信息")) && !string.IsNullOrEmpty(targetID))
                    {
                        WebRequest stepRequest = new WebRequest("http://agent.eju.com/housereal/save?ver=3.0&step=2", FormType.FormUrlEncode, inputEncoding, retEncoding);
                        stepRequest.Cookies = loginCookies;

                        SyncImage(info, stepRequest, targetID);

                        ret = stepRequest.SendWaitString();
                        if (!string.IsNullOrEmpty(ret) && ret.Contains("房源发布成功"))
                        {
                            TargetUrl = string.Format("http://sh.esf.sina.com.cn/detail/{0}", targetID);
                            UpdateCurrentStatus(StandardProgress.Sucess, GetImageError(info), targetID, TargetUrl);
                            return true;
                        }
                        error = GetError(ret);
                        goto erroHanlder;
                        //GetError
                    }
                    if (!string.IsNullOrEmpty(ret))
                    {
                        if (ret.Contains("canAdmin"))
                        {
                            error = "您没有发布二手房的权限";

                        }
                        if (ret.Contains("您已发布过类似信息"))
                        {
                            error = "您已发布过类似信息,请修改房源信息后重新发布";
                        }
                        if (ret.Contains("需要您的进一步确认"))
                        {
                            error = "已有相似房源添加";
                        }
                        if (ret.Contains("立即发布"))
                        {
                            error = "网站上是否可以成功发布此小区信息或者表单信息不正确";
                        }
                    }
                    if (string.IsNullOrEmpty(error))
                    {
                        error = "发布失败。发布消息格式不正确";
                    }
                }
            }
            catch (System.Net.WebException exp)
            {
                error = WebError;
            }
            catch (Exception exp)
            {
                LogCenter.Log("易居客信息提交", exp);
                error = exp.Message;
            }
        erroHanlder:
            UpdateCurrentStatus(StandardProgress.Failed, error);
            return false;
        }

        public override bool DeleteSaleHouse(HouseInfo info, string targetID)
        {
            //添加根据合发码查找 发布号的代码
            return InnerDelete(targetID,"1");
        }

        private bool InnerDelete(string targetID,string tradeType)
        {
            UpdateCurrentStatus(StandardProgress.InitalData);
            try
            {
                if (CheckLogin())
                {
                    WebRequest request = new WebRequest("http://agent.eju.com/house/index?tradetype=" + tradeType, FormType.FormUrlEncode, inputEncoding, retEncoding);
                    request.Cookies = loginCookies;
                    request.AddContent("communityid", "");
                    request.AddContent("currpage", "");
                    request.AddContent("house_delete", targetID + "||");
                    request.AddContent("house_pro", "0");
                    request.AddContent("keyword", "");
                    request.AddContent("order", "");
                    request.AddContent("pp_type", "");
                    request.AddContent("pricerange", "");
                    request.AddContent("status", "");
                    request.AddContent("tradetype", tradeType);
                    UpdateCurrentStatus(StandardProgress.PosData);
                    string ret = request.SendWaitString();
                    if (ret.Contains("删除成功"))
                    {
                        UpdateCurrentStatus(StandardProgress.Sucess, "");
                        return true;
                    }
                    else
                    {
                        UpdateCurrentStatus(StandardProgress.Failed, "删除失败");
                        return false;
                    }
                }
                else
                {
                    UpdateCurrentStatus(StandardProgress.Failed, "登陆失败");
                    return false;
                }
            }
            catch (System.Net.WebException exp)
            {
                UpdateCurrentStatus(StandardProgress.Failed, WebError);
                return false;
            }
        }

        public override bool DeleteRentHouse(HouseInfo info, string targetID)
        {
            return InnerDelete(targetID, "2");
        }

        //public override bool RefreshSaleHouse(HouseInfo info, string targetID)
        //{

        //}
        //public override bool RefreshRentHouse(HouseInfo info, string targetID)
        //{

        //}
        #endregion

        #region HelpFunction
        private string GetError(string strHtml)
        {
            if (!string.IsNullOrEmpty(strHtml))
            {
                Regex regex = new Regex("<p><a href=\"\\S*?\">(<err>[\\S\\s]*?)</a></p>");
                if (regex.IsMatch(strHtml))
                {
                    string str = regex.Match(strHtml).Groups["err"].Value ?? "";
                    if (!string.IsNullOrEmpty(str))
                    {
                        return str;
                    }
                }
            }

            return "";
        }

 


        public void SyncImage(HouseInfo info,WebRequest stepRequest, string houseID)
        {
            try
            {
                retImages.Clear();
                errorImage = 0;
                if (info.Images != null && info.Images.Length > 0)
                {
                    int num2 = 2;//室内图
                   
                    foreach (string url in info.Images)
                    {
                        try
                        {
                            WebRequest request = new WebRequest(url);
                            Stream stream = request.GetResouce();
                            string name = url.Substring(url.LastIndexOf('/') + 1);
                            request = new WebRequest(string.Format("http://agent.eju.com/housepicupload/uploadhousepic?ver=3.0&houseid={0}&client_citycode=sh&pictype=sn", houseID), FormType.MultiPart);

                            request.Cookies = loginCookies;


                            request.AddFile(name, "Filedata", stream);
                            string k = request.SendWaitString();

                            //<script type='text/javascript'>window.parent.callback({"success_flag":"success","img":"http:\/\/get.file.dc.cric.com\/EEJU443b7bf0c9c16a6dc352524a9ee77672_600X450_0_0_5.jpg","picurl":"http:\/\/get.file.dc.cric.com\/EEJU443b7bf0c9c16a6dc352524a9ee77672_600X450_0_0_5.jpg","md5":"EEJU443b7bf0c9c16a6dc352524a9ee77672.jpg","ext":"jpg","pictype":"2","status":"2","picid":"20615827","picuser_id":"415486","table_type":""});</script>
                            //	<script type='text/javascript'>window.parent.callback({"success_flag":"success","img":"http:\/\/get.file.dc.cric.com\/EEJU59628a6498c73ec17d024daf37ae078e_600X450_0_0_5.jpg","picurl":"http:\/\/get.file.dc.cric.com\/EEJU59628a6498c73ec17d024daf37ae078e_600X450_0_0_5.jpg","md5":"EEJU59628a6498c73ec17d024daf37ae078e.jpg","ext":"jpg","pictype":"2","status":"2","picid":"20615884","picuser_id":"415574","table_type":""});</script>


                            string fieldValue = GetImageId(k);

                            if (!k.Contains("status\":\"200\"")
                                || string.IsNullOrEmpty(fieldValue))
                            {
                                errorImage++;
                                //<script language="javascript">document.domain="58.com"; parent.$.c.Uploader.finish(1, '/p1/big/n_21432951094029.jpg', 1);</script>
                            }
                            else
                            {
                                stepRequest.AddContent("pixdata_sn[picid][]", fieldValue);
                                stepRequest.AddContent("pixdata_sn[pictype][]", "sn");
                                stepRequest.AddContent("pixdata_sn[fromtype][]", "2");
                            }
                        }
                        catch
                        {
                            errorImage++;
                        }
                    }
                }
                stepRequest.AddContent("houseid", houseID);
                stepRequest.AddContent("apply", "");
                stepRequest.AddContent("pixcover", "");
                stepRequest.AddContent("deleteData", "");
                stepRequest.AddContent("is_edit", "");
                stepRequest.AddContent("Filedata", "fdfdfd.jpg");
              
            }
            catch (Exception exp)
            {
                LogCenter.Log("易居客上传照片出现异常", exp);
            }
        }

        private string GetImageId(string imgHtml)
        {
            string str = "";
            try
            {
                string pattern = "\"id\":\"(?<value>\\d+?)\"";
               
                Regex regex = new Regex(pattern);
                if (!regex.IsMatch(imgHtml))
                {
                    return str;
                }
                string str3 = regex.Match(imgHtml).Groups["value"].Value ?? "";
                if (!string.IsNullOrEmpty(str3))
                {
                    str = str3.Replace(@"\/", "/");
                }
            }
            catch
            {
            }
            return str;
        }

 

        private string getSiteHouseImg(string strValue)
        {
            string str = "";
            try
            {
                if (string.IsNullOrEmpty(strValue) || !strValue.Contains(":"))
                {
                    return str;
                }
                str = (strValue.Substring(strValue.IndexOf(":") + 1) ?? "").Replace("\"", "");
            }
            catch (Exception exception)
            {

            }
            return str;
        }
        private bool GetTargetID(HouseInfo info)
        {
            try
            {
                string url = "http://agent.eju.com/house/index";
                string str2 = "";
                string str3 = "0室0厅0卫";
                string str4 = "0";
                string str5 = "0";
                string str6 = "0";
                string tradeType = "1";
                string fieldValue = info.Area;
                str4 = info.Room;
                str5 = info.Hall;
                str6 = info.WashRoom;
                if (info.TradeType == TradeType.Rent)
                {
                    tradeType = "2";
                    str2 = info.MonthPrice;// postData.Fields.Find(c => c.FieldName == "rentprice").FieldValue ?? "";
                }
                else
                {
                    str2 = info.Price;// postData.Fields.Find(c => c.FieldName == "saleprice").FieldValue ?? "";
                }
                if (string.IsNullOrEmpty(str4))
                {
                    str4 = "0";
                }
                if (string.IsNullOrEmpty(str5))
                {
                    str5 = "0";
                }
                if (string.IsNullOrEmpty(str6))
                {
                    str6 = "0";
                }
                str3 = str4 + "室" + str5 + "厅" + str6 + "卫";
                WebRequest request = new WebRequest(url, FormType.FormUrlEncode,retEncoding,retEncoding);
                request.Cookies = loginCookies;
                GetEsateInformation(request, info);
                this.doHouseListForm(request, 1, info.Estate, tradeType, "");
                string str8 = "";
                int num = 0;

                str8 = request.SendWaitString();
                if ((!string.IsNullOrEmpty(str8) && str8.Contains("<th><span>操作</span></th>")) && (str8.Contains("符合条件的项目共") && !str8.Contains("符合条件的项目共<b>0</b>套")))
                {
                    //<a href="http://sh.esf.eju.com/view/38995428" target='_blank'>玉兰香苑</a>
                    Regex regex = new Regex("href=\"(?<id>.*?)\" target='_blank'>(?<value>[\\S\\s]*?)</div>");
                    if (regex.IsMatch(str8))
                    {
                        foreach (Match match in regex.Matches(str8))
                        {
                            string tarurl = match.Groups["id"].Value ?? "";
                            string str9 = "";
                            if (!string.IsNullOrEmpty(tarurl))
                            {
                               str9 = tarurl.Substring(tarurl.LastIndexOf("/")+1);
                            }
                            string str10 = match.Groups["value"].Value ?? "";
                            if ((((!string.IsNullOrEmpty(str9) && !string.IsNullOrEmpty(str10)) && str10.Contains(info.Estate ?? "")) && str10.Contains(str2 ?? "")) && str10.Contains(str3 ?? ""))
                            {
                                TargetBySearch= str9;
                                TargetUrl = tarurl;
                                return true;
                            }
                        }
                    }


                }
            }
            catch (Exception exception)
            {
                LogCenter.Log("无法获取网站房源编号,EJU", exception);
            }
            return false;
        }


        private void doHouseListForm(WebRequest request, int pubType, string buildName, string tradeType, string currHouseId)
        {
            try
            {
                request.AddContent("status", "");
                
                request.AddContent("propertype", "");
                request.AddContent("pricerange", "");
                request.AddContent("communityname", buildName ?? "");
                request.AddContent("house_pro", "1");
                request.AddContent("currpage", "1");
                if (!string.IsNullOrEmpty(currHouseId))
                {
                    request.AddContent("del_houseid", currHouseId + "||");
                }
                else
                {
                    request.AddContent("del_houseid", "");
                }
                request.AddContent("del_status", "-1");
                request.AddContent("tradetype", tradeType ?? "");
                request.AddContent("pro", "on");
                if (pubType == 3)
                {
                    request.AddContent("chkall", "on");
                }
                request.AddContent("order", "0");
            }
            catch (Exception exception)
            {
                LogCenter.Log("组装删除房源的表单异常", exception);
            }
        }



        public void GetEsateInformation(WebRequest request, HouseInfo info)
        {
            WebRequest ajax = new WebRequest("http://agent.eju.com/ajax/ajaxgetcommunity?_=1347106021364&key=" + HtmlHelper.UrlEncode(info.Estate));
            ajax.Cookies = loginCookies;
            string ret = ajax.GetResouceStr();
            ret = HtmlHelper.DecodingJSON(ret);
            //'communityid':'4046','communityname':'\u6625\u6e2f\u4e3d\u56ed','viewdistrict':'\u6d66\u4e1c','viewblock':'\u5f20\u6c5f','housesite':'\u76ca\u4e30\u8def55\u5f04'
            Regex reg = new Regex("\\[\"(?<communityid>[^,]*?)\",\".*?\",\"(?<housesite>.*?)\",\"(?<district>.*?)\",\"(?<block>.*?)\",");
            Match ma = reg.Match(ret);
            if (ma.Success)
            {
                request.AddContent("communityname", info.Estate);
                request.AddContent("communityid", ma.Groups["communityid"].Value);
                request.AddContent("district", ma.Groups["district"].Value);
                request.AddContent("block", ma.Groups["block"].Value);
                request.AddContent("housesite", ma.Groups["housesite"].Value);
            }
            else
            {
                LogCenter.LogMessage("易居客小区匹配出错。小区名称:" + info.Estate);
                throw new UnMatchEstateException(info.Estate);
                //request.AddContent("communityname", info.Estate);
                //request.AddContent("communityid", "");
                //request.AddContent("district", "");
                //request.AddContent("block", "");
            }
        }

        public string GetTradeType(HouseInfo info)
        {
            if (info.TradeType == TradeType.Rent)
            {
                return "2";
            }
            return "1";
        }
        public string GetAge(string age)
        {
            int temp = 1;
            int.TryParse(age, out temp);
            return (DateTime.Now.Year - temp).ToString();
        }
        public void GetAgentID()
        {
            WebRequest request = new WebRequest("http://agent.eju.com/housereal/addhouse?propertype=1");
            request.Cookies = loginCookies;
            request.ReturnEncoding = retEncoding;
            string ret = request.GetResouceStr();
            AgentID = HtmlHelper.GetTextOrHiddenValueByName(ret, "agentid");
        }

        public string GetHouseType(HouseInfo info)
        {
            //当前:平房=1,普通住宅=2,商住两用=3,公寓=4,别墅=5,其他=6
            //目标:住宅=1,别墅=2,酒店式公寓=3,老公房=9,厂房仓库=6,其他=7
            switch (info.HouseType)
            { 
                case "1":
                    return "9";
                case "2":
                    return "1";
                case "3":
                    return "1";
                case "4":
                    return "3";
                case "5":
                    return "2";
                case "6":
                    return "7";
            }
            return "1";
        }

        public string GetRentType(HouseInfo info)
        { 
            //当前0.单间出租 1.床位出租 2.整套出租
            //目标 1.整租，2合租 3短租
            switch (info.HireType)
            { 
                case "0":
                    return "2";
                case "1":
                    return "2";
                case "2":
                    return "1";
            }
            return "1";
        }

        public string GetToward(string toward)
        {
            //当前 1:东 2:南 3:西 4:北 5:南北 6:东西 7:东南 8:西南 9:东北 10:西北 11:其他
            //目标 东=1,南=2, 西=3,北=4，东南=5，东北=6，西南=7，西北=8，南北=9，东西=10
            if (toward == "1")
            {
                return "1";
            }
            if (toward == "2")
            {
                return "2";
            }
            if (toward == "3")
            {
                return "3";
            }
            if (toward == "4")
            {
                return "4";
            }
            if (toward == "5")
            {
                return "9";
            }
            if (toward == "6")
            {
                return "10";
            }
            if (toward == "7")
            {
                return "5";
            }
            if (toward == "8")
            {
                return "7";
            }
            if (toward == "9")
            {
                return "6";
            }
            if (toward == "10")
            {
                return "8";
            }
            return "1";
        }

        public string GetDecoration(string dec)
        {
            //当前 1:毛胚 2:简装 3:精装 4:豪装
            //目标  毛坯=1,清水=2,简装=3,中装=4,精装=5,豪装=6
            switch (dec)
            { 
                case "1":
                    return "1";
                case "2":
                    return "3";
                case "3":
                    return "5";
                case "4":
                    return "6";
            }
            return "3";
        }

        public void GetPayment(WebRequest request, HouseInfo info)
        {
            //当前 1:付一押一 2:付二押一 3:付三押一 4:付六押一
            //目标 
            switch (info.PayType)
            {
                case "0":
                    request.AddContent("paymentreq", "-1");
                    request.AddContent("depositreq", "-1");
                    break;
                case "1":
                    request.AddContent("paymentreq", "1");
                    request.AddContent("depositreq", "1");
                    break;
                case "2":
                    request.AddContent("paymentreq", "2");
                    request.AddContent("depositreq", "1");
                    break;
                case "3":
                    request.AddContent("paymentreq", "3");
                    request.AddContent("depositreq", "1");
                    break;
                case "4":
                    request.AddContent("paymentreq", "6");
                    request.AddContent("depositreq", "1");
                    break;
                default:
                    request.AddContent("paymentreq", "-1");
                    request.AddContent("depositreq", "-1");
                    break;
            }
        }

        public void GetPayment( HouseInfo info,out string payment,out string deposit)
        {
            //当前 1:付一押一 2:付二押一 3:付三押一 4:付六押一
            //目标 
            switch (info.PayType)
            {
                case "0":
                    payment = "-1";
                    deposit = "-1";
                    break;
                case "1":
                      payment = "1";
                    deposit = "1";
                    break;
                case "2":
                      payment = "2";
                    deposit = "1";
                    break;
                case "3":
                       payment = "3";
                    deposit = "1";
                    break;
                case "4":
                       payment = "6";
                    deposit = "1";
                    break;
                default:
                       payment = "-1";
                    deposit = "-1";
                    break;
            }
        }
        #endregion

        public override bool CheckDescription(HouseInfo infor, bool isSale, ref string errorInfor)
        {
            if (string.IsNullOrEmpty(infor.Description))
            {
                errorInfor = "说明不能为空";
                return false;
            }

            if (infor.Description.Length < 20)
            {
                errorInfor = "说明必须多于20字";
                return false;
            }
            return true;
        }

        #region 编辑功能
        public override bool OpenEidt(WebBrowserOp op, HouseInfo info)
        {
            try
            {
                if (CheckLogin())
                {


                    if (info.TradeType == TradeType.Sale)
                    {
                        string post = "http://agent.eju.com/housereal/addhouse";
                        foreach (KeyValuePair<string, string> k in loginCookies)
                        {
                            WebBrowserOp.InternetSetCookie(post, k.Key, k.Value);
                        }
                        op.HouseInformation = info;
                        op.Navigate(post);
                        op.Completed += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(op_Sale_Completed);
                    }
                    else
                    {
                        string post = "http://agent.eju.com/housereal/addhouse?tradetype=2";
                        foreach (KeyValuePair<string, string> k in loginCookies)
                        {
                            WebBrowserOp.InternetSetCookie(post, k.Key, k.Value);
                        }
                        op.HouseInformation = info;
                        op.Navigate(post);
                        op.Completed += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(op_Rent_Completed);
                    }

                }
                else
                {
                    return false;
                }
            }
            catch
            {
                op.Navigate("http://agent.eju.com/center/index?ver=3.0");
            }
            return true;
        }
        void op_Sale_Completed(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)
        {
            
            WebBrowserOp cl = sender as WebBrowserOp;
            HouseInfo info = cl.HouseInformation;
            cl.SetValueByID("communityname", info.Estate);

            cl.SetValueByID("buildingarea", info.Area);
            cl.SetValueByID("saleprice", info.Price);
            cl.SetValueByID("model_room", info.Room);
            cl.SetValueByID("model_hall", info.Hall);
            cl.SetValueByID("model_toilet",info.WashRoom);
            cl.SelectByName_Value("propertype",  GetHouseType(info));
            cl.SelectByName_Value("fitment",  GetDecoration(info.Decoration));

            cl.SelectByName_Value("direction",  GetToward(info.Toward));

            cl.SetValueByID("floor", info.CurrentFloor);
            cl.SetValueByID("total_floor", info.Floors);

            cl.SetValueByID("complete", info.Age);

            cl.SetValueByID("housetitle", info.Title);

            cl.SetCKEditorHtml(info.Description);
        }
        void op_Rent_Completed(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)
        {
            WebBrowserOp cl = sender as WebBrowserOp;
            HouseInfo info = cl.HouseInformation;
            cl.SetValueByID("communityname", info.Estate);
            cl.SetValueByID("saleprice", info.MonthPrice);
            string payment = "-1";
            string deposit = "-1";
            GetPayment(info, out payment, out deposit);
            cl.SelectByID_Value("paymentreq", payment);
            cl.SelectByID_Value("depositreq", deposit);

            cl.SetValueByID("buildingarea", info.Area);

            cl.SetValueByID("model_room", info.Room);
            cl.SetValueByID("model_hall", info.Hall);
            cl.SetValueByID("model_toilet", info.WashRoom);
            cl.SelectByName_Value("propertype", GetHouseType(info));
            cl.SelectByName_Value("fitment", GetDecoration(info.Decoration));

            cl.CheckByName_Value("direction_ext", GetToward(info.Toward), true);

            cl.SetValueByID("floor", info.CurrentFloor);
            cl.SetValueByID("total_floor", info.Floors);

            cl.SetValueByID("complete", info.Age);

            cl.SetValueByID("housetitle", info.Title);

            cl.SetCKEditorHtml(info.Description);
        }
        #endregion
    }
}
